package com.eshunda.eshunda_android_demo;

import android.util.Log;

import com.eshunda.eshunda_android_demo.util.HttpUtils;
import com.eshunda.ldt.bean.DetectResult;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class HTTPClient {
    private static final String TAG = "HTTPClient";
    
    // 阿里云API配置（Demo用）
    // 纯活体: fake.market.alicloudapi.com
    private static final String HOST_FAKE = "https://fake.market.alicloudapi.com";
    private static final String PATH_GET_TOKEN = "/getToken";
    private static final String PATH_AUTH = "/verify";

    // 实人认证: esdrp.market.alicloudapi.com
    private static final String HOST_REAL = "https://esdrp.market.alicloudapi.com";
    private static final String PATH_VERIFY = "/verify";
    private static final String METHOD_POST = "POST";

    // 请前往云市场购买( https://market.aliyun.com/detail/cmapi00071585#sku=yuncode6558500001)试用套餐,
    // 购买完成后，进入管理控制台：https://marketnext.console.aliyun.com/bizlist，可以找到APPCODE 字段，复制到下面即可
    // TODO 修改这个为你的appcode
    private static final String APP_CODE = "替换为你的APPCode";
    
    /**
     * 初始化认证，获取token
     * @param authInitData 初始化数据
     * @return 返回的JSON字符串，包含token
     */
    public String authInit(String authInitData) {
        Map<String, String> headers = new HashMap<>();
        // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APP_CODE);
        // 根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        // 需要给X-Ca-Nonce的值生成随机字符串，每次请求不能相同
        headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
        
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("authInit", authInitData);
        
        try {
            HttpUtils.HttpResponse response = HttpUtils.doPost(HOST_FAKE, PATH_GET_TOKEN, METHOD_POST, headers, querys, bodys);
            if (response != null) {
                String result = response.getStringBody();
                Log.d(TAG, "authInit response: " + result);
                return result;
            }
        } catch (Exception e) {
            Log.e(TAG, "authInit error", e);
            e.printStackTrace();
        }
        
        return null;
    }
    
    /**
     * 认证检测结果
     * @param result 检测结果
     * @return 认证结果的JSON字符串
     */
    public String auth(DetectResult result) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APP_CODE);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
        
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("token", result.getToken());
        bodys.put("authVerify", result.getData());
        try {
            Log.d(TAG, "auth Request" + result.getData());
            HttpUtils.HttpResponse response = HttpUtils.doPost(HOST_FAKE, PATH_AUTH, METHOD_POST, headers, querys, bodys);
            if (response != null) {
                String responseStr = response.getStringBody();
                Log.d(TAG, "auth response: " + responseStr);
                return responseStr;
            }else{
                Log.e(TAG, "auth empty");
            }
        } catch (Exception e) {
            Log.e(TAG, "auth error", e);
            e.printStackTrace();
        }
        
        return null;
    }

    /**
     * 实人认证: 获取token
     */
    public String authInitReal(String authInitData, String certName, String certNo) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APP_CODE);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.put("X-Ca-Nonce", UUID.randomUUID().toString());

        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("authInit", authInitData);
        bodys.put("certName", certName);
        bodys.put("certNo", certNo);

        try {
            HttpUtils.HttpResponse response = HttpUtils.doPost(HOST_REAL, PATH_GET_TOKEN, METHOD_POST, headers, querys, bodys);
            if (response != null) {
                String result = response.getStringBody();
                Log.d(TAG, "authInitReal response: " + result);
                return result;
            }
        } catch (Exception e) {
            Log.e(TAG, "authInitReal error", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 实人认证: 提交认证结果
     */
    public String authReal(DetectResult result) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APP_CODE);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.put("X-Ca-Nonce", UUID.randomUUID().toString());

        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();

        if (result != null && result.getData() != null) {
            bodys.put("authData", result.getData());
        }

        try {
            HttpUtils.HttpResponse response = HttpUtils.doPost(HOST_REAL, PATH_VERIFY, METHOD_POST, headers, querys, bodys);
            if (response != null) {
                String responseStr = response.getStringBody();
                Log.d(TAG, "authReal response: " + responseStr);
                return responseStr;
            }
        } catch (Exception e) {
            Log.e(TAG, "authReal error", e);
            e.printStackTrace();
        }

        return null;
    }
}

